package com.kabuda.hot100.链表.medium;


/**
 * @author kabuda
 * @create 2025-02-18 14:09
 * @Description 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。
 * 输入：head = [1,2,3,4,5], n = 2
 * 输出：[1,2,3,5]
 */
public class t19_删除倒数第N个节点 {

    public static void main(String[] args) {
        ListNode headNode = new ListNode(1);
        ListNode listNode2 = new ListNode(2);
        ListNode listNode3 = new ListNode(3);
        ListNode listNode4 = new ListNode(4);
        ListNode listNode5 = new ListNode(5);
        headNode.next = listNode2;
        //listNode2.next = listNode3;
        //listNode3.next = listNode4;
        //listNode4.next = listNode5;
        System.out.println(removeNthFromEnd(headNode, 2));
    }

    /**
     * @author kabuda
     * @date 2025/2/22 16:41
     * @param
     * @return
     * @description 多趟扫描
     */
    public static ListNode removeNthFromEnd(ListNode head, int n) {
        //创建结构节点,next执行头
        ListNode result = new ListNode();
        result.next = head;

        //获取size，倒数第n个就是size-n+1
        ListNode temp = result;
        int size = 0;
        while (temp != null) {
            size++;
            temp = temp.next;
        }
        int index = size - n + 1;

        //删除节点
        temp = result;
        int curIndex = 0;
        while (temp != null) {
            curIndex++;
            if (curIndex >= index-1) {
                if (temp.next != null) {
                    temp.next = temp.next.next;
                }
                break;
            }
            temp = temp.next;
        }
        return result.next;
    }
}






